package com.atguigu.grainmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.grainmall.product.entity.SkuImagesEntity;
import com.atguigu.grainmall.product.entity.SpuInfoDescEntity;
import com.atguigu.grainmall.product.feign.SeckillFeignService;
import com.atguigu.grainmall.product.service.*;
import com.atguigu.grainmall.product.vo.SeckillSkuVo;
import com.atguigu.grainmall.product.vo.SkuItemSaleAttrsVo;
import com.atguigu.grainmall.product.vo.SkuItemVo;
import com.atguigu.grainmall.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.grainmall.product.dao.SkuInfoDao;
import com.atguigu.grainmall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService imagesService;

    @Autowired
    SpuInfoDescService descService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService attrValueService;

    @Autowired
    ThreadPoolExecutor executor;

    @Resource
    SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存sku的基本信息-pms_sku_info
     * @param skuInfoEntity
     */
    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    /**
     * 列表 sku检索
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SkuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        // 判断是否包含见多条件关键字
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq(SkuInfoEntity::getSkuId,key).or().like(SkuInfoEntity::getSkuName,key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        // 判断是否包含见多条件关键字
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq(SkuInfoEntity::getCatalogId,catelogId);
        }
        String brandId = (String) params.get("brandId");
        // 判断是否包含见多条件关键字
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq(SkuInfoEntity::getBrandId,brandId);
        }
        String min = (String) params.get("min");
        // 判断是否包含见多条件关键字
        if(!StringUtils.isEmpty(min)){
            wrapper.ge(SkuInfoEntity::getPrice,min);
        }
        String max = (String) params.get("max");
        // 判断是否包含见多条件关键字
        if(!StringUtils.isEmpty(max)){
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                // 判断数字大不大于0
                if(bigDecimal.compareTo(new BigDecimal("0")) == 1){
                    wrapper.le(SkuInfoEntity::getPrice,max);
                }
            }catch (Exception e){

            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 查出spuid对应的所有信息 品牌的名字
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkusBSpuId(Long spuId) {

        List<SkuInfoEntity> list = this.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId,spuId));

        return list;
    }

    /**
     * 展示当前sku的详情
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        // 异步编排 supplyAsync表示异步优化返回结果的
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(()->{
            // sku基本信息获取
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        },executor);
        // 接受上一步的返回值继续组合执行下边任务 要新建如infoFuture向下逐个拼接放到线程池中执行(为异步) 直接.then为串行化执行
        CompletableFuture<Void> selaAttrFuture = infoFuture.thenAcceptAsync((result) -> {
            // 获取spu的销售属性组合
            List<SkuItemSaleAttrsVo> saleAttrsVos = attrValueService.getSaleAttrsBySpuId(result.getSpuId());
            skuItemVo.setSaleAttrs(saleAttrsVos);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((result) -> {
            // 获取spu的介绍
            SpuInfoDescEntity descEntity = descService.getById(result.getSpuId());
            skuItemVo.setDesc(descEntity);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((result) -> {
            // 获取spu的规格参数
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(result.getSpuId(), result.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);

        // 无关联的任务 直接新建一个异步进行执行 runAsync表示异步无返回值
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            // sku图片信息
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            //3、远程调用查询当前sku是否参与秒杀优惠活动
            R skuSeckilInfo = seckillFeignService.getSkuSeckilInfo(skuId);
            if (skuSeckilInfo.getCode() == 0) {
                //查询成功
                SeckillSkuVo seckilInfoData = skuSeckilInfo.getData("data", new TypeReference<SeckillSkuVo>() {
                });
                skuItemVo.setSeckillSkuVo(seckilInfoData);

                if (seckilInfoData != null) {
                    long currentTime = System.currentTimeMillis();
                    if (currentTime > seckilInfoData.getEndTime()) {
                        skuItemVo.setSeckillSkuVo(null);
                    }
                }
            }
        }, executor);


        // 等待所有任务全部完成后 才返回skuItemVo
        CompletableFuture.allOf(infoFuture,selaAttrFuture,descFuture,baseAttrFuture,imageFuture,seckillFuture).get();

        return skuItemVo;
    }

}
